import { useEffect } from "react";
import { useState } from "react";
import {
  flexRender,
  getCoreRowModel,
  getPaginationRowModel,
  getSortedRowModel,
  useReactTable,
  type SortingState,
} from "@tanstack/react-table";
import { cn } from "@/lib/utils";
import { virTableInit } from "@/api/view/pages/generate_api";
import { columns } from "./generate_table_ui";
import { Button } from "@/components/ui/btn/button1";
import { Label } from "@/components/ui/label/label";

interface GenerateTableProps {
  searchBatch: string;
  selectedType: string;
  options: GenerateRowProps[];
  setOptions: (options: GenerateRowProps[]) => void;
}

const defineClassName = {
  with: "grid-cols-[1fr_1fr_1fr_1fr_1fr_1fr_2fr_1fr_1fr]",
};

export default function GenerateTable({
  options,
  setOptions,
}: GenerateTableProps) {
  const [sorting, setSorting] = useState<SortingState>([]);
  const [pagination, setPagination] = useState({ pageIndex: 0, pageSize: 10 });

  useEffect(() => {
    setOptions(virTableInit);
  }, []);

  const table = useReactTable({
    data: options,
    columns,
    state: { sorting, pagination },
    onSortingChange: setSorting,
    onPaginationChange: setPagination,
    getCoreRowModel: getCoreRowModel(),
    getSortedRowModel: getSortedRowModel(),
    getPaginationRowModel: getPaginationRowModel(),
    initialState: { pagination: { pageSize: 10 } },
  });

  return (
    <div className="flex h-full w-full flex-col gap-4">
      <div className="grid h-full w-full grid-rows-[1fr_auto]">
        <table className="grid max-h-full min-h-0 grid-rows-[minmax(0,50px)_minmax(0,1fr)] border-t border-b">
          <thead className="grid">
            {table.getHeaderGroups().map((headerGroup) => (
              <tr
                key={headerGroup.id}
                className={cn("grid border-b", defineClassName.with)}
              >
                {headerGroup.headers.map((header) => (
                  <th
                    key={header.id}
                    onClick={header.column.getToggleSortingHandler()}
                    className={cn(
                      "grid",
                      header.column.getCanSort() ? "cursor-pointer" : "",
                    )}
                  >
                    <div className="mx-2 flex items-center-safe">
                      {flexRender(
                        header.column.columnDef.header,
                        header.getContext(),
                      )}
                      {{ asc: " ↑", desc: " ↓" }[
                        header.column.getIsSorted() as string
                      ] ?? null}
                    </div>
                  </th>
                ))}
              </tr>
            ))}
          </thead>
          <tbody className="overflow-auto [&::-webkit-scrollbar]:hidden">
            {table.getRowModel().rows.map((row) => (
              <tr
                key={row.id}
                className={cn("grid h-50 border-b", defineClassName.with)}
              >
                {row.getVisibleCells().map((cell) => (
                  <td
                    key={cell.id}
                    className="flex h-full w-full overflow-hidden"
                  >
                    {flexRender(cell.column.columnDef.cell, cell.getContext())}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>

        <div className="flex flex-row items-center">
          <Button
            variant="secondary"
            onClick={() => table.previousPage()}
            disabled={!table.getCanPreviousPage()}
          >
            上一页
          </Button>
          <Label>第 {pagination.pageIndex + 1} 页</Label>
          <Button
            variant="secondary"
            onClick={() => table.nextPage()}
            disabled={!table.getCanNextPage()}
          >
            下一页
          </Button>
        </div>
      </div>
    </div>
  );
}
